import json
from urllib.parse import unquote,urlencode
import requests
import time
import re
import execjs
from express.tenxun import logininfo
# import js2py

# @todo    python 执行 JavaScript 文件
# @param   file      js 文件路径
# @param   function  要执行的js方法
# @param   *param    传入js的参数个数不定

def execJs(file,function,*param):
    f = open(file, 'r', encoding='utf-8')
    js = execjs.compile(f.read())
    f.close()
    return js.call(function,*param)

def main(url,dr):
    login_message = logininfo.updaelogin()
    # login_message['access_token']='53_--8zQUHCop-ZLV37tQuzGWZUGHvy34XFKKZyAFFbM7wOVo0JSIZ6f_hSBa_e-k2lxLY3rIUfCbOOPzLUfmescSu4khY3_-LiozKRnWcskMY'
    # login_message['vusession'] = '0zVHaKq-Xrws23BvwpRQbw..'
    print(login_message)

    vinfoparam={
        'spsrt':'1',
        'charge':'0',
        'defaultfmt':'auto',
        'otype':'ojson',
        'platform':'10201',
        'sdtfrom':'v1010',
        'defnpayver':'1',
        'appVer':'3.5.57',
        'host':'v.qq.com',
        'refer':'v.qq.com',
        'sphttps':'1',
        'spwm':'4',
        'defn':'fhd',    #清晰度
        'fhdswitch':'0',
        'show1080p':'1',
        'isHLS':'1',
        'dtype':'3',
        'sphls':'2',
        'spgzip':'1',
        'dlver':'2',
        'drm':'32',
        'hdcp':'0',
        'spau':'1',
        'spaudio':'15',
        'defsrc':'2',
        'encryptVer':'9.1',
        'fp2p':'1',
        'spadseg':'3',

    }
    gid = 'e2ddfc31be9959f3f9b81c56a84220a8'
    unid= '47d54c44091a11eb981ca0424b63310a'
    # *******************************************************************************
    # todo 初始连接网页中获取vid ，有一部分vid 在url中，有一部分不在url中，通过这种方法进行通用查找
    r   = requests.get(url)
    r.encoding =r.apparent_encoding
    vurl = re.search('<link rel=\"canonical\" href=\"([\s\S]*?)\"',r.text).groups()[0]
    vid                      = vurl.split('/')[-1].split('.')[0]
    # *******************************************************************************
    tm                       = str(time.time()).replace('.','')[:10]
    ckey                     = execJs('cKey.js','main',url,gid,vid,tm)
    # flowid                   = execJs('cKey.js','flowid')  不重要


    vinfoparam['unid']        =unid
    vinfoparam['guid']       = gid
    vinfoparam['flowid']     = 'acb6a78081fd183a8dd806271e058fac_10201'#前面随机后面固定
    vinfoparam['ehost']      = url  #视频的直接地址
    vinfoparam['logintoken'] = '{"main_login":"wx","openid":"oXw7q0Oje_ex7KL_bbafqsoO3paM","appid":"wxa75efa648b60994b","access_token":"'+login_message['access_token']+'","vuserid":"1758049538","vusession":"'+login_message['vusession']+'"}'
    vinfoparam['vid']        = vid
    vinfoparam['tm']         = tm
    vinfoparam['cKey']       = ckey

    load={"buid":"vinfoad",
          "adparam":"",
          "vinfoparam":  urlencode(vinfoparam)}
    print(load)
    url = "https://vd.l.qq.com/proxyhttp"
    r = requests.post(url, data=json.dumps(load))
    vinfo = r.text.replace('\\', '').replace('null', '0')
    print(vinfo)
    ur =re.findall('{\"url\":\"(https:[\s\S]*?ver=4)',vinfo)#获取4个m3u8地址
    print(ur)
    print("****************************************************************")
    m3u8_url =ur[0]
    pos = m3u8_url.rindex('/')
    m3u8 = requests.get(m3u8_url).text
    print(m3u8)

    list =m3u8.replace('\n','').replace('\'','').split(',')
    count = 0
    for i in list:
        count +=1
        url =m3u8_url[0:pos]+'/'+i
        print(url)
        try:
            r = requests.get(url)
            r.raise_for_status()
            name =str(count).zfill(3)+'.ts'
            print(name)
            f=open('./reset/'+dr+'/'+name,'wb')
            f.write(r.content)
            f.close()
        except:
            pass








url='https://v.qq.com/x/cover/mzc00200mp8vo9b/y0041hif2qg.html'
url={
     '14':'https://v.qq.com/x/cover/mzc00200mp8vo9b/j0041bc5ulb.html',
     '15':'https://v.qq.com/x/cover/mzc00200mp8vo9b/x0041qqe42w.html'}

for ur in url:
    print(url[ur])
    main(url[ur],ur)




